/******************************************************************************
*GenerateTorrent.c is a program to create a torrent file with extension .storrent file 
*Input: filename.extension, TrackerIP address and Tracker PortNumber
*Output: filename.extension.storrent
*Author:Aaditya Singhvi
*Date:16th Nov 2010
*SpartaTorrent.All Rights Reserved (c) 2010 
*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "crc.h"

#define PARTSIZE 65536
#define BUFF 30

/*Function to remove \r*/
 void rm_nline_char(char *in_string, int size)
 {
 	int j;
 	
 	for(j=0;j<size;j++){
 		if(in_string[j]=='\n'){
 			in_string[j]='\0';
 		}
 	}
 }

/* Main Function*/

int main()
{
	FILE *fp;
	long int offset;
	long int fileSize;
	int pieces;
	int lpsize=0;
	crc filecrc;
	
	char torrentfile[BUFF];
	struct file_part *filehead;

	char filename[BUFF];
	char trackerIP[BUFF];
	char trackerport[BUFF];
	 
	printf("\nEnter the file name:");
	fflush(stdout);	
	fgets(filename,BUFF,stdin);	
	printf("File name is: %s",filename);
	fflush(stdout);	
	rm_nline_char(filename,BUFF);
	
	printf("\nEnter the Tracker Ip:");
	fflush(stdout);	
	fgets(trackerIP,BUFF,stdin);
	printf("Tracker IP is: %s",trackerIP);
	fflush(stdout);	
	rm_nline_char(filename,BUFF);

	printf("\nEnter the Tracker Port:");
	fflush(stdout);	
	fgets(trackerport,BUFF,stdin);	
	printf("Tracker Port is: %s\n",trackerport);
	fflush(stdout);	
	rm_nline_char(filename,BUFF);
		
	filecrc=calculatecrc(filename);
	
	fp=fopen(filename,"rb+");
	fseek (fp,0,SEEK_END);
  	
	printf("\nFile Created and Opened");
	fileSize = ftell(fp);
  	rewind (fp);
	
	pieces= (int) fileSize/PARTSIZE;
	lpsize=(int) fileSize%PARTSIZE;
	
	if(lpsize==0){
		//do nothing
		}
	else{
		pieces=pieces+1;
		}
	
	printf("\nNumber of parts: %d\nSize of Last part is: %d\n",pieces,lpsize);
		
	fclose(fp);	
	
	sprintf(torrentfile,"%s%s",filename,".storrent");	// Adds .storrent extension to filename
	fp=fopen(torrentfile,"w");				
	
	/*To write to the file with .storrent extension */	
	fprintf(fp,"%s%s","TrackerIP ",trackerIP);
	fprintf(fp,"%s%s","TrackerPort ",trackerport);	
	fprintf(fp,"%s %ld","FileSize ",fileSize);	
	fprintf(fp,"%s %d","\nPieces ",pieces);	
	fprintf(fp,"%s %ld","\nPieceSize ",PARTSIZE);
	fprintf(fp,"%s%d","\nLastPieceSize ",lpsize);
	fprintf(fp,"%s%d","\nFilecrc ",filecrc);	
	fprintf(fp,"\n%s.sTorrent file Created by SpartaTorrent (c) 2010\nAll Rights Reserved",filename);
	printf("\n %s.sTorrent file Created by SpartaTorrent (c) 2010\n",filename);	
	fclose(fp);
	

return 0;
}
